const jwt = require('jsonwebtoken')
const { createUser, getUserInfo, updateById } = require('../service/user.service')
const { userRegisterError, userLoginError } = require('../constant/err.type')
const { JWT_SECRET } = require('../config/default')

class UserController {
  async register (ctx, next) {
    const { username, password, email } = ctx.request.body
    try {
      const res = await createUser({
        username,
        password,
        email
      })

      ctx.body = {
        code: 0,
        message: '用户注册成功',
        result: {
          id: res.id,
          username: res.username,
          email: res.email
        }
      }
    } catch (err) {
      console.error('用户注册失败', err)
      return ctx.app.emit('error', userRegisterError, ctx)
    }
  }

  async login (ctx, next) {
    const { email } = ctx.request.body
    try {
      const { password, ...res } = await getUserInfo({ email })
      ctx.body = {
        code: 0,
        message: '用户登录成功',
        result: {
          token: jwt.sign(res, JWT_SECRET, { expiresIn: '1d' })
        }
      }
    } catch (err) {
      console.err('用户登录失败', err)
      return ctx.app.emit('error', userLoginError, ctx)
    }
  }

  async changePassword (ctx, next) {
    const id = ctx.state.user.id
    const password = ctx.request.body.password

    if (await updateById({ id, password, })) {
      ctx.body = {
        code: 0,
        message: '修改密码成功',
        result: ''
      }
    } else {
      ctx.body = {
        code: '10007',
        message: '修改密码失败',
        result: ''
      }
    }
  }

  async getLoginUser (ctx, next) {
    const user = ctx.state.user
    if (user) {
      ctx.body = {
        code: 0,
        message: '获取当前登录用户',
        result: user
      }
    } else {
      ctx.body = {
        code: '10008',
        message: '获取当前登录用户失败',
        result: ctx.state.user
      }
    }

  }
}

module.exports = new UserController()
